/**
 * Copyright (c) 2018 开源 All rights reserved.
 * <p>
 * https://www.chengcang.com
 * <p>
 * 版权所有，侵权必究！
 */

package com.chengcang.admin.modules.security.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.chengcang.admin.common.utils.UserUtils;
import com.chengcang.admin.modules.sys.entity.*;
import com.chengcang.common.enums.DataTypeEnum;
import com.chengcang.admin.modules.security.dao.SysUserTokenDao;
import com.chengcang.admin.modules.security.entity.SysUserTokenEntity;
import com.chengcang.admin.modules.security.service.ShiroService;
import com.chengcang.admin.modules.security.user.SecurityUser;
import com.chengcang.admin.modules.security.user.UserDetail;
import com.chengcang.admin.modules.sys.dao.*;
import com.chengcang.common.enums.SuperAdminEnum;
import com.chengcang.admin.modules.sys.service.SysDictDataService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class ShiroServiceImpl implements ShiroService {
    @Autowired
    private SysMenuDao sysMenuDao;
    @Autowired
    private SysUserDao sysUserDao;
    @Autowired
    private SysDeptDao sysDeptDao;
    @Autowired
    private SysTenantDao sysTenantDao;
    @Autowired
    private SysUserTenantDao sysUserTenantDao;
    @Autowired
    private SysUserTokenDao sysUserTokenDao;
    @Autowired
    private SysRoleDataScopeDao sysRoleDataScopeDao;
    @Autowired
    private SysRoleUserDao sysRoleUserDao;
    @Autowired
    private SysDictDataService sysDictDataService;

    @Override
    public Set<String> getUserPermissions(UserDetail user) {
        //系统管理员，拥有最高权限
        List<String> permissionsList = new ArrayList<>();
        if (UserUtils.isSuperAdmin()) {
            if (null == SecurityUser.getTenantId()) {
                permissionsList = sysMenuDao.getPermissionsList();
            } else if (1L == SecurityUser.getTenantId()) {
                permissionsList = sysMenuDao.getPermissionsListByTenantId(SecurityUser.getTenantId());
            }
        } else if (UserUtils.isTenantAdmin()) {
            permissionsList = sysMenuDao.getPermissionsListByTenantId(SecurityUser.getTenantId());
        } else {
            permissionsList = sysMenuDao.getUserPermissionsList(user.getId());
        }

        //用户权限列表
        Set<String> permsSet = new HashSet<>();
        for (String permissions : permissionsList) {
            if (StringUtils.isBlank(permissions)) {
                continue;
            }
            permsSet.addAll(Arrays.asList(permissions.trim().split(",")));
        }

        return permsSet;
    }

    @Override
    public SysUserTokenEntity getByToken(String token) {
        return sysUserTokenDao.getByToken(token);
    }

    @Override
    public SysUserEntity getUser(Long userId) {
        SysUserEntity sysUserEntity = sysUserDao.selectById(userId);
        SysRoleUserEntity sysRoleUserEntity = sysRoleUserDao.selectOne(new LambdaQueryWrapper<SysRoleUserEntity>().eq(SysRoleUserEntity::getUserId, userId));
        Optional.ofNullable(sysRoleUserEntity).ifPresent(o -> sysUserEntity.setRoleId(sysRoleUserEntity.getRoleId()));
        Optional.ofNullable(sysUserEntity.getDeptId()).ifPresent(o -> {
            SysDeptEntity sysDeptEntity = sysDeptDao.selectById(o);
            Optional.ofNullable(sysDeptEntity).ifPresent(o1 -> {
                if (StringUtils.isNotBlank(o1.getPids()) && !Objects.equals("0", sysDeptEntity.getPids())) {
                    sysUserEntity.setDeptIds(o1.getPids() + "," + o1.getId());
                } else {
                    sysUserEntity.setDeptIds(String.valueOf(o1.getId()));
                }
            });
        });
        Optional.ofNullable(sysUserEntity.getDefaultTenantId()).ifPresent(o -> {
            SysTenantEntity sysTenantEntity = sysTenantDao.selectById(o);
            Optional.ofNullable(sysTenantEntity).ifPresent(o1 -> {
                sysUserEntity.setDefaultTenantType(o1.getTenantType());
            });
        });
        return sysUserEntity;
    }

    @Override
    public List<Long> getDataScopeList(Long userId) {
        return sysRoleDataScopeDao.getDataScopeList(userId);
    }

    @Override
    public List<UserTenant> getUserTenantList(Long id) {

        List<UserTenant> userTenants = sysUserTenantDao.selectUserTenant(id);
        for (UserTenant userTenant : userTenants) {
            userTenant.setUserTypeName(sysDictDataService.getValue(DataTypeEnum.USER_TYPE, String.valueOf(userTenant.getUserType())));
        }
        return userTenants;
    }
}